function getUrlParam(name) {
    var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)');
    var r = window.location.search.substr(1).match(reg);
    if (r != null) return decodeURIComponent(r[2]);
    return null;
}

$(function () {

    // Check age gate
    if ($.cookie('agegate') !== 'pass') {
        document.location.replace('/Content/pages/age-gate/index.html')
        return
    }

    $(".fancybox").fancybox({
        'transitionIn': 'none',
        'transitionOut': 'none',
        'scrolling': "no"
    });

    $('.trade-box-item .itemtxtbox').each(function () {
        var teaser = $('.item-text', this)
        $(this).css({
            bottom: -teaser.height() - 16
        })
    })

    $('img[data-src]').each(function (){
        var img = $(this)
        img.css('background-image', `url(${img.data('src')})`)
    })

    // 格式化数据, 将英文数据本地化
    ;
    (function () {
        var _convertLength = function (data) {
                data = $.trim(data)
                var regInch = /^(\d+ )?\d+(\/\d+)?"$/,
                    regInternational = /^[\d\.]+ cm$/i,
                    inchCm = 2.54

                var parts = data.split('//'),
                    lengthStr = '0',
                    length = 0

                if (parts.length == 2) {
                    lengthStr = parts[1]
                    length = parseFloat($.trim(lengthStr))
                    lengthStr = length + ' 厘米'

                } else if ((/^[\d\.]+ cm$/i).test(data)) {
                    val = parseFloat(data)
                    lengthStr = val + ' 厘米'

                } else {
                    // Convert inch
                    let a, b, c, val
                    if ((/^\d+"$/).test(data)) {
                        // 英寸 1
                        val = parseFloat(data)
                    } else if ((/^\d+\/\d+"$/).test(data)) {
                        // 英寸 2
                        parts = data.split('/')
                        val = parseFloat(parts[0])
                        val = val / parseFloat(parts[1])
                    } else if ((/^\d+ \d+\/\d+"$/).test(data)) {
                        // 英寸 3
                        parts = data.replace(/^\d+ (\d+\/\d+)"$/, '$1').split('/')
                        val = parseFloat(data) * (parseFloat(parts[0]) / parseFloat(parts[1]))
                    } else if ((/^\d+( rg)?$/i).test(data)) {
                        // 无单位, 雪茄环规, 1环=1/64英寸
                        val = parseFloat(data) * 1/64
                    } else {
                        console.info('数据格式不匹配, 取消转换: ' + data)
                        val = data
                    }
                    if (val === data) {
                        lengthStr = data
                    } else {
                        val *= inchCm
                        val = Math.round(val * 10) / 10
                        lengthStr = val + ' 厘米'
                    }
                }

                return lengthStr
            },
            _convertTime = function (data) {
                if (data.indexOf(' 分钟') == -1) {
                    console.error('数据格式不符合规范, 取消转换: ' + data)
                    return data
                }

                var parts = data.replace(/：/g, ':').split(':'),
                    h = parseInt(parts[0]),
                    m = parseInt(parts[1]),
                    time = ''
                if (parts.length === 1) {
                    m = h
                } else if (!isNaN(h) && h > 0) {
                    m += h * 60
                }
                if (isNaN(m) || m <= 0) {
                    m = '-'
                }
                time = (m + ' 分钟')

                return time
            }

        //
        $('#info .filters').each(function () {
            var filter = $(this),
                label = filter.find('.label').text(),
                val = '',
                data = filter.data('orignal-data') ? filter.data('orignal-data') : filter.find('.value').text(),
                methods = {
                    '长度': _convertLength,
                    '直径': _convertLength,
                    '享用时间': _convertTime
                }

            label = $.trim(label)
            if (methods[label]) {
                val = methods[label](data)
                filter.find('.value').text(val)

                if (!filter.data('orignal-data')) {
                    filter.data('orignal-data', data)
                }
            }
        })
    })()

    // 缩略放大效果
    ;(function(){
        var scaleRate = 2.5
        var container = $('#visual')
        if (container.length === 0) {
            return
        }


        var _initX = 0, _initY = 0,
            _vw = 0, _vh = 0,
            _pw = 0, _ph = 0,
            _theImg = null,
            _waiting = 0
        var _mouseMove = function (evt){
            var _mx = (evt.pageX - _initX) / _vw
            var _my = (evt.pageY - _initY) / _vh
            _mx = (_mx < 0 ? 0 : _mx > 1 ? 1 : _mx)
            _my = (_my < 0 ? 0 : _my > 1 ? 1 : _my)

            _theImg.css({
                left: _mx * _pw,
                top: _my * _ph
            })

            console.log('move', {
                offsetX: evt.pageX,
                offsetY: evt.pageY,
                _mx, _my,
                left: _mx * _pw,
                top: _my * _ph
            })
        }
        var _removeZoomArea = function () {
            $('.zoom-container').remove()
        }
        var _createZoomArea = function (img) {
            var node = $('<div class="zoom-container" style="position: absolute; z-index: 99;width: 100%; height: 100%;left: 0;top: 0;overflow: hidden; background-color: #FFF;" ></div>')
            var imgWidth = img.width() * scaleRate
            var imgHeight = img.height() * scaleRate
            img = img.clone()
            img.css({
                width: imgWidth,
                height: imgHeight,
                position: 'relative'
            })
            node.append(img)
            node.mousemove(_mouseMove)
                .mouseleave(_removeZoomArea)
                .appendTo(container)

            _initX = node.offset().left
            _initY = node.offset().top
            _vw = node.width()
            _vh = node.height()
            _pw = _vw - imgWidth
            _ph = _vh - imgHeight
            _theImg = img

            console.log('zoom area initailed', {_initX, _initY, _vw, _vh, _pw, _ph})
        }
        container.css('position', 'relative')
        var gallery = $('.swiper-container.gallery-top', container)
        gallery.mouseenter(function (){
            _waiting = setTimeout(function (){
                var img = $('.swiper-slide-active img', gallery)
                _createZoomArea(img.eq(0))
            }, 500)
        })
        gallery.mouseleave(function (){
            clearTimeout(_waiting)
        })
        $('.swiper-container.gallery-thumbs').css('z-index', 199)

    })()

    // Convert cigar describe text line wrap
    ;(function (){
        $('.page_wrapper .txtline p').each(function (){
            var txt = $(this)
            txt.html(txt.text().replace(/\|/g, '<br/>'))
        })
    })()

})
